package rnxutils

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"io"
	"strings"
	"time"
)

func ParseRinexTime(t0 time.Time, format string) string {
	s := format
	tokens := gobase.ParseTokens(format, ' ')
	for _, token := range tokens {
		if t0.IsZero() {
			s = strings.ReplaceAll(s, token, gobase.AddSuffixForWidth("", len(token), " "))
		} else {
			if rs, ok := gobase.GetDateTimeKeyValue(strings.ToLower(token), t0); ok {
				s = strings.ReplaceAll(s, token, rs)
			}
		}
	}
	return s
}

func SplitWithWidth(s string, suffix string, widthlst ...int) (strs []string, ok bool) {
	s, ok = gobase.TryTrimSuffix(s, suffix)
	if !ok {
		return
	}

	if len(widthlst) == 0 {
		s = gobase.ReplaceMultiSpace2One(gobase.Trim(s), " ")
		strs = strings.Split(s, " ")
		return
	}

	startIdx := 0
	for i := 0; i < len(widthlst); i++ {
		s0 := s[startIdx : startIdx+widthlst[i]]
		s0 = gobase.Trim(s0)
		strs = append(strs, s0)
		startIdx += widthlst[i]
	}
	return
}

func WriteFixedWidthStr(w io.Writer, s string, width int) error {
	s = gobase.AddSuffixForWidth(s, width, " ")
	if len(s) > width {
		s = s[:width]
	}
	_, err := w.Write([]byte(s))
	return err
}

func Join2String(v ...interface{}) string {
	var bb strings.Builder
	for _, v0 := range v {
		bb.WriteString(fmt.Sprintf("%v", v0))
	}
	return bb.String()
}

func WriteRinexFloat(w io.Writer, width int, v float64, pn int) error {
	s := fmt.Sprintf(Join2String("%.", pn, "f"), v)
	s = gobase.AddPrefixForWidth(s, width, " ")
	if len(s) > width {
		s = s[:width]
	}

	_, err := w.Write([]byte(s))
	return err
}

func DelNonNumberChar(s string) string {
	strs := []rune(s)
	rval := make([]rune, 0, len(strs))
	for _, chr := range strs {
		if chr >= '0' && chr <= '9' {
			rval = append(rval, chr)
		}
	}
	return string(rval)
}
